import PieChart from '../PieChart/PieChart';

export default class IncidentHandler {
    constructor() {
        this.chart = null;
        this.infoObj = null;
        this._marker = null;
        this._popup = null;
        this._moveFeature = null
        this._clickFeature = null
    }

    loadData(map, isInitChart) {
        let that = this;
        minemap.util.getJSON('../data/incident.json', function (error, data) {
            const infoObj = data ? data || [] : [];
            that.infoObj = infoObj;
            if (isInitChart) {
                that.updateChart();
            }
        });
    }

    updateChart() {
        this.chart = new PieChart('incident-chart', this.infoObj);
    }

    getInfoObj() {
        return this.infoObj;
    }

    getChart() {
        return this.chart;
    }

    setVisible(map) {
        map.setLayoutProperty('5a3ea454892d4824b622cdabb48950a2', 'visibility', 'visible');
        this._clear(map);
    }

    setUnvisible(map) {
        map.setLayoutProperty('5a3ea454892d4824b622cdabb48950a2', 'visibility', 'none');
        this._clear(map);
    }

    onMouseMoveHandler(map, feature) {
        if (!map) {
            return;
        }
        if (this._popup) {
            this._popup.remove();
            this._popup = null;
        }
        if (!feature) {
            this._moveFeature = null;
        } else {
            this._moveFeature = feature;
            if (this._clickFeature) {
                const clickCoord = this._clickFeature.geometry.coordinates;
                const moveCoord = this._moveFeature.geometry.coordinates;
                if (clickCoord[0] == moveCoord[0] && clickCoord[1] == moveCoord[1]) {
                    this._moveFeature = null;
                } else {
                    if (this._marker) {
                        this._marker.remove();
                        this._marker = null;
                    }
                    this._clickFeature = null;
                }
            }
        }

        if (this._moveFeature) {
            let html = `<span>${this._moveFeature.properties['edesc'] || ''}</span>`;
            let el = document.createElement('div');
            el.className = 'function-info';
            el.innerHTML = html;
            this._popup = new minemap.Popup({
                closeOnClick: true,
                closeButton: false,
                offset: [0, 0]
            }).setLngLat(this._moveFeature.geometry.coordinates).setDOMContent(el).addTo(map);
        }
    }



    _clear(map) {
        if (map) {
            if (this._marker) {
                this._marker.remove();
            }
            if (this._popup) {
                this._popup.remove();
            }
        }
        this._marker = null;
        this._popup = null;
        this._moveFeature = null
        this._clickFeature = null
    }
};